const url = require('url'),//   get
      util = require('util'),
      query = require("querystring");    //解析POST请求
const pname = 'module';//   父目录名称

//  404 请求错误
exports.noneFound = (res,file,apphtml) => {
    apphtml = typeof(apphtml) == 'string'? apphtml:"";
    res.writeHead(404,{'Content-Type': 'text/html'});
    res.end(`
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>404 Not Found!</title>
        </head>
        <body>
            <h4>404 Not Found!</h4>
            <p>The file `+file+`</p>
            `+apphtml+`
            <p><a href="/index.html">返回首页</a></p>
        </body>
        </html>
    `);
}
//  通用错误处理
exports.unerror = (res,apphtml,num) => {
    apphtml = typeof(apphtml) == 'string'? apphtml:"";
    num = typeof(apphtml) == 'string'? apphtml:404;
    res.writeHead(num,{'Content-Type': 'text/html'});
    res.end(`
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>`+num+`</title>
        </head>
        <body>
            `+apphtml+`
        </body>
        </html>
    `);
}
//  常规文件文件检测
exports.ckFile = (urlStr) => {
    var tpl = ['html','js','css'];
    var udata = url.parse(urlStr);
    urlStr = udata['pathname'];
    //  检查最后一个元素
    var arr = urlStr.split('/');
    var app = arr[arr.length-1];
    if(app.indexOf('.')>-1) return true;
    //  存在迅速返回
    for(var k in tpl){if(urlStr.indexOf('.'+tpl[k])>-1) return true;}
    return false;
}
//  默认-index文件检测
exports.index = (urlStr,type)   => {
    type = typeof(type) == 'undefined'? 'index.html':type;
    //if(url.charAt(url.length-1) != '/') return url;
    if(urlStr == '/') return urlStr+type;
    var arr = urlStr.split('/');
    var len = arr.length-1;
    if(arr[len] == '') urlStr += type;
    return urlStr;
}
//  url ?get参数检测-消除get参数忽略
exports.getCk = (urlStr,type) => {
    type = typeof(type) == 'undefined'? '.js':type;
    var tpl = ['?','#'];
    if(urlStr.indexOf('?')>-1 || urlStr.indexOf('#')){
        var str = urlStr.indexOf('?')>-1? '?':'#';
        var arr = urlStr.split(str);
        //return arr[0];
        urlStr = arr[0];
    }
    if(urlStr.indexOf(type) == -1) urlStr += type;
    return urlStr;
}
//  表单数据 POST/GET
exports.bind = (req,res) =>{
    var data = {'__GET':null,'__POST':null};
    try{
        if(req.method == "GET"){
            data['__GET'] = url.parse(req.url,true).query;
            data['method'] = 'GET';
        }else{
            var postdata = "";
            var POST = {};
            req.addListener("data",function(postchunk){
                postdata += postchunk;
            });
            req.addListener("end", function () {
                POST = query.parse(postdata);
                data['__POST'] = POST;// 方式1)，2)方法无法将异步数据回写
                //console.log(POST);
            });
            //data['__POST'] = POST;// 方式2)
            data['method'] = 'POST';
        }
        //  session值绑定
        req['session'] = this.session(req,res);
        var S = req['session'];
        data['__SESSION'] = S.toJson();
    }catch(e){console.log(e);}
    return data;
}
//  cookie 实现方式
exports.session = (req,res) =>{
    return new http_session_obj(req,res);
}
function http_session_obj(req,res){
    //this.sessionString = res.getHeader('Set-Cookie');
    this.sessionString = res.getHeader('set-cookie');    
    //  设置session的值- jquery 风格化数据处理
    this.value = function(k,v){
        if(!k) return '';
        var data = this.SESSION;
        if(util.isNullOrUndefined(v)){//获取
            if(data[k]) return data[k];
            return '';
        }else{
            data[k] = v;
            var str = this.toString(data);
            if(str) res.setHeader('Set-Cookie',str);
            return true;
        }
    };
    this.set = function(k,v){
        var data = this.SESSION;
        if(k && !util.isNullOrUndefined(v)){
            data[k] = v;
            var str = this.toString(data);
            if(str) res.setHeader('Set-Cookie',str);
            return true;
        }
        return false;
    };
    this.get = function(k){
        if(!k) return '';
        var data = this.SESSION;
        if(data[k]) return data[k];
        return '';
    };
    // 解析SESSION的值为 JSON, 自定义值用于测试
    /*	
        pgv_pvid=5035653020; _ga=GA1.1.788700616.1467694855; _uuid=a3ac74e9fa1fed93; pma_lang=zh_CN; pma_collation_connection
        =utf8_unicode_ci; pma_iv-1=RuT0qOncw7gH19vEp5gS8w%3D%3D; pmaUser-1=brHS3uIf%2B1PG2WeG%2FjV4mw%3D%3D;
        PHPSESSID=q7nofoqevcjt4mnttacb4ig5c0; __qc_wId=172
    */
    this.reset = function(newres){
        if(util.isObject(newres)){
            this.res = newres;
            this.sessionString = newres.getHeader('set-cookie');
        }
    };
    this.toJson = function(str){
        if(util.isNullOrUndefined(str) || !str) str = this.sessionString;
        var data = {};
        if(!util.isNullOrUndefined(str)){
            str = str.replace(new RegExp(' ','g'),'');
            str = str.replace(new RegExp(';','g'),'","');
            str = str.replace(new RegExp('=','g'),'":"');
            str = `{"${str}"}`;
            data = JSON.parse(str);
        }
        return data;
    };
    /*
        { "k1":"v1","k2":"v2"} => k1=v1; k2=v2
    */
    this.toString = function(data){
        var str = '';
        if(util.isObject(data)){
            str = JSON.stringify(data);
            str = str.replace(new RegExp('{','g'),'');
            str = str.replace(new RegExp('}','g'),'');
            str = str.replace(new RegExp('"','g'),'');
            str = str.replace(new RegExp(',','g'),';');
            str = str.replace(new RegExp(':','g'),'=');
        }
        return str;
    };
    this.SESSION = this.toJson();
}